import type { AxiosInstance, AxiosRequestConfig, AxiosResponse, InternalAxiosRequestConfig } from "axios";
import axios from "axios";
import { useUserStore } from "@/stores";
import { Authorization, Bearer, UserId } from "@/config";
import type { ResultData } from "@/typings";

export interface CustomAxiosRequestConfig extends InternalAxiosRequestConfig {
  noLoading?: boolean;
}

const axiosConfig = {
  baseURL: import.meta.env.VITE_PROXY + import.meta.env.VITE_API_URL,
  timeout: 50000
};

class HttpService {
  private service: AxiosInstance;

  public constructor(axiosConfig: AxiosRequestConfig) {
    this.service = axios.create(axiosConfig);

    /**
     * @description 请求拦截器
     */
    this.service.interceptors.request.use((config: CustomAxiosRequestConfig) => {
      const useUser = useUserStore();
      if (config.headers && typeof config.headers.set === "function") {
        config.headers.set(Authorization, Bearer + useUser.token);
        config.headers.set(UserId, useUser.userInfo.id);
      }
      return config;
    });

    /**
     * @description 响应拦截器
     */
    this.service.interceptors.response.use((response: AxiosResponse) => {
      const { data } = response;
      return data;
    });
  }

  get<T>(url: string, config?: AxiosRequestConfig): Promise<ResultData<T>> {
    return this.service.get(url, config);
  }
  post<T>(url: string, data?: object, config?: AxiosRequestConfig): Promise<ResultData<T>> {
    return this.service.post(url, data, config);
  }
  put<T>(url: string, data?: object, config?: AxiosRequestConfig): Promise<ResultData<T>> {
    return this.service.put(url, data, config);
  }
  delete<T>(url: string, config?: AxiosRequestConfig): Promise<ResultData<T>> {
    return this.service.delete(url, config);
  }
}

export default new HttpService(axiosConfig);
